package com.ruibang.glass.material.service.impl.cp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.material.constant.Constants;
import com.ruibang.glass.material.domain.req.ChangeGradeReq;
import com.ruibang.glass.material.entity.MaterialALLInventoryManagement;
import com.ruibang.glass.material.entity.MaterialContentLot;
import com.ruibang.glass.material.entity.cp.MaterialChangeGrade;
import com.ruibang.glass.material.feign.CamundaApi;
import com.ruibang.glass.material.mapper.MaterialContentLotMapper;
import com.ruibang.glass.material.mapper.cp.MaterialChangeGradeMapper;
import com.ruibang.glass.material.service.GMaterialALLInventoryManagementService;
import com.ruibang.glass.material.service.cp.MaterialChangeGradeService;
import com.ruibang.glass.material.service.impl.CommonService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 品级调整 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-04-15
 */
@Service
public class MaterialChangeGradeServiceImpl extends ServiceImpl<MaterialChangeGradeMapper, MaterialChangeGrade> implements MaterialChangeGradeService {


    @Autowired
    private CamundaApi camundaApi;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private CommonService commonService;
    @Autowired
    private MaterialContentLotMapper materialContentLotMapper;

    @Autowired
    private GMaterialALLInventoryManagementService materialInventoryManagementService;

    @Override
    public IPage<MaterialChangeGrade> getPage(ChangeGradeReq changeGradeReq) {
        LambdaQueryWrapper<MaterialChangeGrade> queryWrapper = Wrappers.<MaterialChangeGrade>lambdaQuery();
        if (StringUtils.isNotBlank(changeGradeReq.getApplyUser())) {
            queryWrapper.like(MaterialChangeGrade::getApplyUser, changeGradeReq.getApplyUser());
        }
        if (StringUtils.isNotBlank(changeGradeReq.getContentCode())) {
            queryWrapper.like(MaterialChangeGrade::getContentCode, changeGradeReq.getContentCode());
        }
        if (StringUtils.isNotBlank(changeGradeReq.getLotCode())) {
            queryWrapper.like(MaterialChangeGrade::getLotCode, changeGradeReq.getLotCode());
        }
        if (changeGradeReq.getApplyStartTime() != null) {
            queryWrapper.ge(MaterialChangeGrade::getApplyTime, changeGradeReq.getApplyStartTime());
        }
        if (changeGradeReq.getApplyEndTime() != null) {
            queryWrapper.le(MaterialChangeGrade::getApplyTime, changeGradeReq.getApplyEndTime());
        }
        Page<MaterialChangeGrade> materialChangeGradePage = baseMapper.selectPage(new Page<>(changeGradeReq.getPageNo(), changeGradeReq.getPageSize()),
                queryWrapper.orderByDesc(MaterialChangeGrade::getCreateTime)
        );
        if (CollectionUtils.isEmpty(materialChangeGradePage.getRecords())) {
            return materialChangeGradePage;
        }
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = materialChangeGradePage.getRecords().stream().map(MaterialChangeGrade::getId).collect(Collectors.toList());
        Map<String, Integer> statusMap = null;
        Map<String, String> processMap = null;
        Map<String, String> approveStatusMap = null;
        Map<String, String> userIdMap = null;
        Map<String, String> nodeName = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            statusMap = resultBody.getData().stream().collect(Collectors.toMap(BpmProcessInstanceStatus::getBusinessKey, BpmProcessInstanceStatus::getStatus, (s1, s2) -> s1));
            processMap = resultBody.getData().stream().collect(Collectors.toMap(BpmProcessInstanceStatus::getBusinessKey, BpmProcessInstanceStatus::getProcessInstanceId, (s1, s2) -> s1));
            approveStatusMap = resultBody.getData().stream().collect(Collectors.toMap(BpmProcessInstanceStatus::getBusinessKey, BpmProcessInstanceStatus::getResult, (s1, s2) -> s1));
            userIdMap = resultBody.getData()
                    .stream()
                    .filter(status -> status.getUserId() != null)
                    .collect(Collectors.toMap(
                            BpmProcessInstanceStatus::getBusinessKey,
                            BpmProcessInstanceStatus::getUserId,
                            (s1, s2) -> s1
                    ));
            nodeName = resultBody.getData().stream().collect(Collectors.toMap(BpmProcessInstanceStatus::getBusinessKey, BpmProcessInstanceStatus::getNodeName, (s1, s2) -> s1));

        }
        for (MaterialChangeGrade qualityContact : materialChangeGradePage.getRecords()) {
            if (statusMap != null) {
                qualityContact.setStatus(statusMap.get(qualityContact.getId())==null?"":statusMap.get(qualityContact.getId()).toString());
            }
            if (processMap != null) {
                qualityContact.setProcessId(processMap.get(qualityContact.getId()));
            }
//            if (approveStatusMap != null) {
//                qualityContact.setApproveStatus(approveStatusMap.get(qualityContact.getId()));
//            }
            if (nodeName != null) {
                qualityContact.setNodeName(nodeName.get(qualityContact.getId()));
            }
            if (approveStatusMap != null) {
                String userId = userIdMap.get(qualityContact.getId());
                if (StringUtils.isNotBlank(userId)) {
                    if (userMap.get(userId) != null) {
                        qualityContact.setApproveUser(userMap.get(userId).toString());
                        qualityContact.setApproveUserId(userId);
                    }

                }
            }
        }
        return materialChangeGradePage;
    }

    @Override
    public void addMaterialChangeGrade(MaterialChangeGrade materialChangeGrade) {
        baseMapper.insert(materialChangeGrade);
        BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
        instanceCreate.setBusinessKey(materialChangeGrade.getId());
        instanceCreate.setMenuId(materialChangeGrade.getMenuId());
        //发起流程
        if (StringUtils.isNotBlank(materialChangeGrade.getApplyId())) {
            Map<String, Object> variables = new HashMap<>();
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, materialChangeGrade.getApplyId());
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, materialChangeGrade.getId());
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, materialChangeGrade.getMenuId());
            instanceCreate.setVariables(variables);
        }
        commonService.startProcess(instanceCreate);
    }


    @Override
    public List<MaterialContentLot> getMaterialContentLotList() {
        List<MaterialContentLot> materialContentLots = materialContentLotMapper.selectList(Wrappers.<MaterialContentLot>lambdaQuery()
                .select(MaterialContentLot::getLotId, MaterialContentLot::getContentCode, MaterialContentLot::getLotCode));
        return materialContentLots;
    }


    @Override
    public void processNotice(String businessId) {
        MaterialChangeGrade materialChangeGrade = baseMapper.selectById(businessId);
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(Arrays.asList(businessId));
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            BpmProcessInstanceStatus process = resultBody.getData().get(0);
            if (materialChangeGrade.getApproveStatus().equals(Constants.TWO_STR)) {
                List<MaterialALLInventoryManagement> list = materialInventoryManagementService.list(Wrappers.<MaterialALLInventoryManagement>lambdaQuery()
                        .eq(MaterialALLInventoryManagement::getBatchNumber, materialChangeGrade.getBatchNumber())
                        .eq(MaterialALLInventoryManagement::getATypeShelf, materialChangeGrade.getContentCode())
                );
                if (CollectionUtils.isNotEmpty(list)){
                    for (MaterialALLInventoryManagement materialALLInventoryManagement:list){
                        materialALLInventoryManagement.setModelGrade(materialChangeGrade.getAfterGrade());
                        materialInventoryManagementService.updateById(materialALLInventoryManagement);
                    }
                }
            }
        }
    }
}
